<template>
    <view style="background:#f3f4f6; padding-bottom: 130rpx; height: 100vh;">
        <!-- 状态栏的占位 -->
        <view class="headers">
            <!-- 返回按钮 -->
            <view class="back-button" @click="goBack">
                <u-icon name="arrow-left" size="20" color="#000"></u-icon>
            </view>
            <!-- 显示合集树名称 -->
            <view class="collection-name" v-if="titleName">
                {{ titleName }}
            </view>
        </view>
        <view class="content">
            <view class="map-container">
                <!-- 地图组件 -->
                <map
                    id="myMap"
                    :longitude="longitude || 116.397428" 
                    :latitude="latitude || 39.909236"
                    :scale="scale || 15"
                    :markers="markers"
                    :polyline="polyline"
                    :controls="controls"
                    style="width: 100%; height: 100%;"
                    @markertap="markerTap"
                    @controltap="controlTap"
                    @regionchange="regionchange"
                    show-location="true"
                    enable-scroll="true"
                    enable-zoom="true"
                    enable-rotate="false"
                    :key="mapKey"
                ></map>
                <view class="control-group">
                    <view class="control-btn" style="border-radius: 10rpx 10rpx 0 0;" @click="zoomIn">+
                    </view>
                    <view class="control-btn" style="border-radius:  0 0 10rpx 10rpx" @click="zoomOut">-
                    </view>
                </view>
            </view>
        </view>
        
        <authuserInfo ref="auth_userInfo"></authuserInfo>
        <authPhone ref="auth_phone"></authPhone>
        <!-- 引入自定义tabBar -->
        <custom-tabbar :currentIndex="0"></custom-tabbar>
    </view>
</template>

<script>
// 引入组件
import authuserInfo from "@/components/auth-userinfo/auth-userinfo.vue"
import authPhone from "@/components/auth-phone/auth-phone.vue"
import CustomTabbar from '@/components/tabbar/tabbar.vue'

export default {
    // 注册组件
    components: {
        authuserInfo,
        authPhone,
        CustomTabbar
    },
    data() {
        return {
            // 地图中心点坐标
            longitude: '',
            latitude: '',
            province: '',
            // 缩放级别
            scale: 8,
            // 标记点数组
            markers: [],
            // 路线
            polyline: [],
            // 控件
            controls: [],
            // 地图组件key，用于强制刷新
            mapKey: 0,
            dictValue: 5,
            is_loading: true,
            error_num: 1,
            page_loding: 'loading',
            information_list: [],
            userInfo: uni.getStorageSync('userInfo'),
            information_form: {
                page: 0,
                searchType: 0,
                lat: '',
                lon: '',
                distance: '5',
                size: '5',
                keyword: '',
            },
            // 数据加载状态
            dataLoaded: false,
            // 合集树名称
            titleName: ''
        }
    },
    onLoad(e) {
        console.log("页面加载参数:", e);
        if (e && e.information_ids) {
            // 从参数中获取titleName
            if (e.titleName) {
                this.titleName = e.titleName;
            }
            // 页面加载时立即执行init方法
            this.init(e.information_ids);
        } else {
            console.warn("未接收到 information_ids 参数");
            uni.showToast({
                title: "参数错误",
                icon: "none"
            })
        }
    },
    
    onReady() {
        // 页面准备完成后再检查一次数据
        console.log("页面准备完成，当前标记点数量:", this.markers.length);
        // 确保地图在页面准备完成后刷新
        if (this.dataLoaded && this.markers.length > 0) {
            // 延迟刷新以确保地图组件完全加载
            setTimeout(() => {
                this.refreshMap();
            }, 300);
        }
    },
    
    methods: {
        // 返回上一页
        goBack() {
            console.log("点击返回按钮");
            // 首先尝试使用 navigateBack
            uni.navigateBack({
                delta: 1,
                fail: (err) => {
                    console.log("navigateBack 失败:", err);
                    // 如果 navigateBack 失败，尝试使用 redirectTo 返回首页
                    uni.redirectTo({
                        url: '/pages/index/index',
                        fail: (err2) => {
                            console.log("redirectTo 失败:", err2);
                            // 如果 redirectTo 也失败，使用 switchTab
                            uni.switchTab({
                                url: '/pages/index/index',
                                fail: (err3) => {
                                    console.log("switchTab 失败:", err3);
                                    // 最后尝试 reLaunch
                                    uni.reLaunch({
                                        url: '/pages/index/index'
                                    });
                                }
                            });
                        }
                    });
                }
            });
        },
        
        // 手动刷新地图
        refreshMap() {
            console.log("手动刷新地图，当前标记点数量:", this.markers.length);
            // 只有在有标记点数据时才刷新地图
            if (this.markers.length > 0) {
                this.mapKey += 1;
                this.$forceUpdate();
                
                // 获取地图上下文并重新设置中心点
                this.$nextTick(() => {
                    setTimeout(() => {
                        try {
                            const mapCtx = uni.createMapContext('myMap', this);
                            if (this.longitude && this.latitude) {
                                mapCtx.moveToLocation({
                                    longitude: this.longitude,
                                    latitude: this.latitude
                                });
                            }
                        } catch (error) {
                            console.error("刷新地图位置失败:", error);
                        }
                    }, 100);
                });
            }
        },
        
        // 验证图片URL是否可能有效（简单检查）
        isValidImageUrl(url) {
            if (!url || typeof url !== 'string') {
                return false;
            }
            
            // 检查是否是有效的URL格式
            return url.startsWith('http') || url.startsWith('/static/');
        },
        
        // 放大地图
        zoomIn() {
            if (this.scale < 20) {
                this.scale += 1;
                this.refreshMap();
            }
        },
        
        // 缩小地图
        zoomOut() {
            if (this.scale > 4) {
                this.scale -= 1;
                this.refreshMap();
            }
        },
        // 地图区域变化事件
        regionchange(e) {
            console.log('地图区域变化', e.type);
        },
        // 控件点击事件
        controlTap(e) {
            console.log('点击控件', e);
        },
        // 标记点点击事件
        markerTap(e) {
            const marker = this.markers.find(m => m.id === e.markerId);
            if (marker) {
                uni.navigateTo({
                    url: "/packageB/information/information?information_id=" + marker.ids + '&lat=' + marker.latitude + '&lon=' + marker.longitude
                })
            }
        },
        async init(treeIds) {
            console.log("init方法被调用，传入的treeIds:", treeIds);
            // 清空之前的标记点
            this.markers = [];
            // 重置地图key
            this.mapKey = 0;
            // 重置数据加载状态
            this.dataLoaded = false;
            
            try {
                // 修复参数传递问题
                const res = await this.$http.to_http('system/tree/listByIds', treeIds.split(','), 'POST', false);
                const data = res.data;
                console.log("接口返回的完整数据:", data);
                if (data.code != 200) {
                    console.error("接口返回错误:", data.msg);
                    uni.showToast({
                        title: "系统维护中",
                        icon: "none"
                    });
                    return;
                }
                console.log("==223==>", data);
                if (data.data && data.data.length > 0) {
                    console.log("接收到的数据数量:", data.data.length);
                    
                    // 用于跟踪相同位置的标记点
                    const positionMap = new Map();
                    
                    data.data.forEach((el, index) => {
                        console.log("处理第" + (index+1) + "个数据:", el);
                        
                        // 验证必要字段
                        if (!el.longitude || !el.latitude) {
                            console.warn("数据缺少经纬度信息:", el);
                            return;
                        }
                        
                        // 检查图片路径是否有效
                        let iconPath = el.roundedImage || '/static/location.png';
                        if (!iconPath || iconPath.trim() === '' || !this.isValidImageUrl(iconPath)) {
                            iconPath = '/static/location.png';
                            console.warn("图片路径无效，使用默认图标");
                        }
                        
                        // 检查是否在同一位置，如果是则稍微偏移
                        const positionKey = `${el.longitude},${el.latitude}`;
                        let offset = 0;
                        if (positionMap.has(positionKey)) {
                            offset = positionMap.get(positionKey) + 0.0001;
                            positionMap.set(positionKey, offset);
                            console.log("检测到相同位置的标记点，进行偏移处理");
                        } else {
                            positionMap.set(positionKey, 0);
                        }
                        
                        const marker = {
                            id: index + 1, // 使用索引作为ID
                            longitude: el.longitude + offset,
                            latitude: el.latitude + offset,
                            title: el.name || '未知地点',
                            iconPath: iconPath,
                            ids: el.id,
                            width: 44,
                            height: 44,
                            anchor: { x: 0.5, y: 0.5 },
                            callout: {
                                content: el.name || '未知地点',
                                color: '#3d3d3d',
                                padding: 5,
                                borderWidth: 2,
                                borderColor: '#fff',
                                borderRadius: 10,
                                fontSize: 16,
                                display: 'ALWAYS'
                            }
                        }
                        
                        console.log("创建标记点:", marker);
                        this.markers.push(marker);
                    });
                    
                    // 设置地图中心点为所有标记点的中心
                    if (this.markers.length > 0) {
                        if (this.markers.length === 1) {
                            // 只有一个标记点
                            this.longitude = this.markers[0].longitude;
                            this.latitude = this.markers[0].latitude;
                        } else {
                            // 计算多个标记点的中心点
                            let minLng = Math.min(...this.markers.map(m => m.longitude));
                            let maxLng = Math.max(...this.markers.map(m => m.longitude));
                            let minLat = Math.min(...this.markers.map(m => m.latitude));
                            let maxLat = Math.max(...this.markers.map(m => m.latitude));
                            
                            this.longitude = (minLng + maxLng) / 2;
                            this.latitude = (minLat + maxLat) / 2;
                            
                            // 根据标记点分布调整缩放级别
                            let lngDiff = maxLng - minLng;
                            let latDiff = maxLat - minLat;
                            let maxDiff = Math.max(lngDiff, latDiff);
                            
                            if (maxDiff < 0.001) {
                                this.scale = 17;
                            } else if (maxDiff < 0.01) {
                                this.scale = 15;
                            } else {
                                this.scale = 13;
                            }
                        }
                        console.log("设置地图中心点:", this.longitude, this.latitude, "缩放级别:", this.scale);
                    }
                    
                    console.log("总共创建了", this.markers.length, "个标记点");
                    
                    // 标记数据加载完成
                    this.dataLoaded = true;
                    
                    // 确保在DOM更新后刷新地图
                    this.$nextTick(() => {
                        // 延迟刷新以确保地图组件完全加载
                        setTimeout(() => {
                            this.refreshMap();
                        }, 300);
                    });
                } else {
                    console.warn("返回的数据为空");
                    uni.showToast({
                        title: "暂无数据",
                        icon: "none"
                    });
                }
            } catch (error) {
                console.error("请求失败:", error);
                uni.showToast({
                    title: "数据加载失败",
                    icon: "none"
                });
            }
        },
    }
}
</script>

<style scoped lang="scss">
.content {
    background: transparent;
    padding-bottom: 10px;
    box-sizing: border-box;
    color: #333;
    position: absolute;
    z-index: 2;
    width: 100%;
    top: 230rpx;
    height: calc(100vh - 230rpx);
}

.headers {
    background-image: url('http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/56ea2705-adb5-4a12-848c-8fbe12e9a179.png?Expires=4907190184&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=mJQMCS3RjUe%2FrD8Q%2FiLLXIHmk3A%3D');
    height: 500rpx;
    width: 100%;
    background-size: cover;
    padding-top: 100rpx;
    position: fixed;
    z-index: 1;
    top: 0;
}

.back-button {
    position: absolute;
    top: 120rpx;
    left: 30rpx;
    width: 90rpx;
    height: 60rpx;
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 4;
    /* 添加点击效果 */
    transition: background-color 0.3s;
}

.back-button:active {
    background-color: rgba(230, 230, 230, 0.8);
}

.collection-name {
    position: absolute;
    top: 120rpx;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #25772f;
    text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.3);
    z-index: 3;
}

.map-container {
    width: 100%;
    height: 100%;
    position: relative;
}

///地图
.control-group {
    display: flex;
    flex-direction: column;
    position: fixed;
    left: 10rpx;
    top: 45%;
}

.control-btn {
    width: 80rpx;
    height: 90rpx;
    background-color: #25772f;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 60rpx;
    color: #fff;
    font-weight: bold;
    cursor: pointer;
}
</style>